package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * //获取所有的一级分类
     * <p>
     * model相当于是页面
     */
    @GetMapping({"/", "index.html"})
    public String indexPage(Model model) {
        List<CategoryEntity> catagories = categoryService.getLevel1Catagories();
        //给页面提供属性
        model.addAttribute("catagories", catagories);
        return "index";
    }

    @ResponseBody
    @RequestMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    /**
     * 测试
     * <p>
     * <p>
     * ①若使用lock()，若业务还没执行完，那么会自动给锁续期（redisson一开始默认的锁过期时间是30s，续期是指续成30s，每隔“看门狗时间/3”的时间就续期一次，即默认每10s就续期一次）。
     * ②若使用lock(10, TimeUnit.SECONDS)，像这种自己指定了过期时间的锁（此处是10s），那么到期后不会续期，所以要特别留意，业务时间不能比锁的时间短，不然锁就没意义了。
     * <p>
     * 推荐使用后者，即自己指定过期时间
     */
    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        //1、获取同一把锁，只要锁的名字一样，就是同一把锁，
        RLock lock = redissonClient.getLock("my-lock");
        //2、加锁，lock()是阻塞式等待
        lock.lock();
        try {
            System.out.println("加锁成功，执行业务" + Thread.currentThread().getId());
            //这里执行sleep是模拟这个业务需要30s
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //3、解锁
            System.out.println(Thread.currentThread().getId() + "释放锁");
            lock.unlock();
        }
        return "hello";
    }


    /**
     * 保证一定能读到最新数据，修改期间，写锁是一个排他锁（互斥锁,共享锁）。读锁是一个共享锁
     * 写锁没释放，读就必须等待
     * <p>
     * 读 + 读 ：相当于无锁，并发读，只会在redis中记录好，所有当前的读锁，他们都会同时加锁成功
     * 写 + 读 ：等待写锁释放
     * 写 + 写：阻塞方式
     * 读 + 写：有读锁，写也需要等待
     * 只要有写的存在，都必须等待！
     */
    @GetMapping("/read")
    @ResponseBody
    public String readValue() {

        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = readWriteLock.readLock();
        rLock.lock();
        try {
            System.out.println("读锁加锁成功。。。。" + Thread.currentThread().getId());
            s = stringRedisTemplate.opsForValue().get("writeValue");
            Thread.sleep(30000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("读锁释放" + Thread.currentThread().getId());
        }
        return s;
    }

    /**
     * 尝试写
     */
    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {

        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = readWriteLock.writeLock();
        try {
            //1、改数据加写锁，读数据加读锁
            rLock.lock();
            System.out.println("写锁加锁成功。。。。" + Thread.currentThread().getId());
            s = UUID.randomUUID().toString();
            Thread.sleep(10000);
            stringRedisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
            System.out.println("写锁释放" + Thread.currentThread().getId());
        }
        return s;
    }


    /**
     * 信号量可以做”分布式限流“
     * 信号量大于0，就能正常执行业务
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {

        RSemaphore park = redissonClient.getSemaphore("park");
        //尝试获取信号量
        boolean b = park.tryAcquire();
        if (b) {
            //执行业务
        } else {
            return "error";
        }
        return "ok";

    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();
        return "走了";
    }

    /**
     * 模拟”闭锁“
     *
     * 模拟顺序：
     * 先执行lockdoor，然后就很进入阻塞状态，然后执行5次/gogogo/id（此处的id随便填写，重复也可以），
     * 但是要执行五次请求，达到五次请求后就会输出”放假了“，即停止阻塞了
     */
    @GetMapping("/lockdoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {

        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);//设置door要”达到“的数值
        door.await();//等待door达到数值，达到之前一直阻塞
        return "放假了";
        //door最终会删掉
    }

    @GetMapping("/gogogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable int id) {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();//执行一次，计数器就+1
        return id + "号走了";
    }


}
